/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sims.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import sims.entity.Configurator;

/**
 *
 * @author BinhMV
 */
public class Configuration {

    public static Configurator readConfig() throws FileNotFoundException, IOException {

        String line;
        String host = null;
        String port = null;
        String databasename = null;
        String username = null;
        String pass = null;
        BufferedReader r = new BufferedReader(new FileReader("config.txt"));
        if(r.ready()){
        while ((line = r.readLine()) != null) {
            if (line.startsWith("#Host:")) {
                int start = line.indexOf(":");
                host = line.substring(start + 1);
            } else if (line.startsWith("#Port:")) {
                int start = line.indexOf(":");
                port = line.substring(start + 1);
            } else if (line.startsWith("#Databasename:")) {
                int start = line.indexOf(":");
                databasename = line.substring(start + 1);
            } else if (line.startsWith("#Username:")) {
                int start = line.indexOf(":");
                username = line.substring(start + 1);

            } else if (line.startsWith("#Password:")) {
                int start = line.indexOf(":");
                pass = line.substring(start + 1);
            }
        }
        }
        r.close();
        Configurator config = new Configurator(host, port, databasename, username, pass);
        return config;
    }
    
    public static String saveConfig(Configurator option){
        BufferedWriter w = null;
        try {
            w = new BufferedWriter(new FileWriter("config.txt",false));
            w.write("#Host:"+option.getHostname()+"\n");
            w.write("#Port:"+option.getPort()+"\n");
            w.write("#Databasename:"+option.getDatabasename()+"\n");
            w.write("#Username:"+option.getUsername()+"\n");
            w.write("#Password:"+option.getPass()+"\n");
            return "Save option sucessful !";
        } catch (IOException ex) {
            return "save option unsuccessful !";
        } finally {
            try {
                w.close();
            } catch (IOException ex) {
                Logger.getLogger(Configuration.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
    }
}